package com.wzp.server;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengpeng.wang
 */
public class ReorderList1 {

    /**
     * 方法一：线性表
     * 因为链表不支持下标访问，所以我们无法随机访问链表中任意位置的元素。
     * <p>
     * 因此比较容易想到的一个方法是，我们利用线性表存储该链表，然后利用线性表可以下标访问的特点，直接按顺序访问指定元素，重建该链表即可。
     */
    public static void reorderList(ListNode head) {
        if (head == null) {
            return;
        }
        List<ListNode> nodeList = new ArrayList<>();
        ListNode node = head;
        while (node != null) {
            nodeList.add(node);
            node = node.next;
        }
        int left = 0, right = nodeList.size() - 1;
        while (left < right) {
            nodeList.get(left).next = nodeList.get(right);
            left++;

            if (left == right) {
                break;
            }
            nodeList.get(right).next = nodeList.get(left);
            right--;
        }
        nodeList.get(left).next = null;
        System.out.println(head);
    }

    public static void reorderList1(ListNode head) {
        if (head == null) {
            return;
        }
        // 找到中间位置
        ListNode mid = middleNode(head);
        ListNode left = head;
        ListNode right = mid.next;
        mid.next = null;

        right = reverseList(right);
        mergeList(left, right);
        System.out.println(head);
    }

    private static ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        System.out.println(node1);
        reorderList(node1);
    }

    public static ListNode middleNode(ListNode head) {
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    public static void mergeList(ListNode l1, ListNode l2) {
        ListNode l1_tmp, l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;

            l1.next = l2;
            l1 = l1_tmp;

            l2.next = l1;
            l2 = l2_tmp;
        }
    }

}
